package com.share.finance.risk.third.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.share.common.utils.IpUtil;
import com.share.common.utils.ThreadUtil;
import com.share.finance.risk.common.model.sys.LocalRequest;
import com.share.finance.risk.common.model.sys.ThirdRequest;
import com.share.finance.risk.third.aop.CacheApiData;
import com.share.finance.risk.third.mapper.ChannelRequestLogMapper;
import com.share.finance.risk.third.mapper.ThirdRequestLogMapper;
import com.share.finance.risk.third.model.db.ChannelRequestLog;
import com.share.finance.risk.third.model.db.InterfaceConfig;
import com.share.finance.risk.third.model.db.ThirdRequestLog;
import com.share.finance.risk.third.service.AsyncDealService;
import com.share.finance.risk.third.service.IInterfaceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.Executor;

/**
 * executorService.execute提交任务，execute（Runnable run）日志信息可以正常打印，且日志只能打印到控制台。
 * executorService.submit提交任务，submit（callable call）不会打印日志信息。
 */
@Slf4j
@Service
public class AsyncDealServiceImpl implements AsyncDealService {
    private Executor executorService = ThreadUtil.getExecutor();

    @Autowired
    private ThirdRequestLogMapper thirdRequestLogMapper;

    @Autowired
    private ChannelRequestLogMapper channelRequestLogMapper;

    @Autowired
    private IInterfaceConfigService interfaceConfigService;

    @Autowired
    private CacheApiData cacheApiData;

    @Override
    public int channelRequestLogServiceSaveLog(InterfaceConfig configPo, ThirdRequest req, String httpParam, String result, boolean isCache, long costTime) {
        executorService.execute(() -> {
            ChannelRequestLog po = new ChannelRequestLog();
            po.setProcessTime(costTime);
            po.setName(req.getName());
            po.setProductCode(req.getProductCode());
            po.setIntId(req.getIntId());
            po.setSessionId(req.getSessionId());
            po.setPhoneNo(req.getPhoneNo());
            po.setIdCard(req.getIdCard());
            po.setBankCard(req.getBankCard());
            po.setRequestData(httpParam);
            po.setResponseData(result);
            po.setFromCache(isCache ? 1 : 0);
            po.setCacheKey(cacheApiData.getCacheKey(req, configPo));//再次计算key值
            po.setFeeStatus(interfaceConfigService.calcFee(configPo.getIntId(), result));//计算费用的逻辑
            po.setCreateTime(new Date());

            Object eval = JSONPath.read(result, configPo.getSucessFlag());
            String successCode = eval == null ? null : eval.toString();
            po.setSuccessFieldValue(successCode);//把字段提取出来

            channelRequestLogMapper.insert(po);
        });
        return 1;
    }

    @Override
    public int thirdRequestLogServiceSaveLog(ThirdRequest req, Object res, long costTime, String reqIp) {
        executorService.execute(() -> {
            ThirdRequestLog po = new ThirdRequestLog();
            po.setProcessTime(costTime);
            po.setCycleNum(req.getCycleNum());
            po.setProductCode(req.getProductCode());
            po.setSessionId(req.getSessionId());
            po.setIntIds(req.getIntIds());
            po.setRequestData(JSON.toJSONString(req));
            po.setResponseData(res == null ? null : JSON.toJSONString(res));
            po.setExeIp(IpUtil.getIp());
            po.setReqIp(reqIp);
            po.setCreateTime(new Date());
            thirdRequestLogMapper.insert(po);
        });
        return 1;
    }

    @Override
    public int localRequestLogServiceSaveLog(LocalRequest req, Object res, long costTime, String reqIp) {
        executorService.execute(() -> {
            ThirdRequestLog po = new ThirdRequestLog();
            po.setProcessTime(costTime);
            po.setCycleNum(req.getCycleNum());
            po.setProductCode(req.getProductCode());
            po.setSessionId(req.getSessionId());
            po.setIntIds("-99");
            po.setRequestData(JSON.toJSONString(req));
            po.setResponseData(res == null ? null : JSON.toJSONString(res));
            po.setExeIp(IpUtil.getIp());
            po.setReqIp(reqIp);
            po.setCreateTime(new Date());
            thirdRequestLogMapper.insert(po);
        });
        return 1;
    }

}
